﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using UFC.Common;
using UFC.DBUtility;

namespace MESGateWay.WinSMESContainer
{
    /// <summary>
    /// Erp订单优先级中间表（mfgorder_info）同步更新到MES表（mfgorder）
    /// </summary>
    public class ErpMfgorderPriorityToMes
    {
        public void RunErpMfgorderPrioritySync()
        {
            if (DateTime.Now.Hour == 23)//定时23点更新
            {
                DataTable dt = getErpMfgorderPriorityData();
                var arrList = new ArrayList();
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        LogHelp.WriteLog("【" + row["mfgordername"] + "】订单优先级由【" + row["prioritycodename"] + "】更新为【" + row["aprio"] + "】");
                        arrList.Add(string.Format("update mfgorder set priorityid='{0}' where mfgordername='{1}'", row["prioritycodeid"], row["mfgordername"]));
                    }
                }
                if (arrList.Count > 0)
                {
                    OracleHelper.ExecuteSqlTran(arrList);
                    LogHelp.WriteLog("Erp订单优先级中间表（mfgorder_info）同步更新到MES表（mfgorder）成功更新" + arrList.Count + "条数据");
                }
            }
        }

        private DataTable getErpMfgorderPriorityData()
        {
            var selectSQL = @"SELECT m.mfgordername,m.qty,p2.prioritycodeid,p.prioritycodename,mi.* FROM mfgorder m 
            LEFT JOIN mfgorder_info mi ON mi.aufnr=m.mfgordername
            LEFT JOIN prioritycode p ON p.prioritycodeid=m.priorityid
            LEFT JOIN prioritycode p2 ON p2.prioritycodename=trim(mi.aprio)
            WHERE m.priorityid IS NOT NULL AND trim(mi.aprio) IS NOT NULL AND p2.prioritycodeid IS NOT NULL
            AND p.prioritycodename<>trim(mi.aprio) ORDER BY trim(mi.aprio)";
            return OracleHelper.QueryTable(selectSQL, null);
        }
    }
}
